<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            background-color: blueviolet;
            width: 150px;
            height: 150px;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 1;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
        // 2. 拖拽-事件监听式绑定事件版
        var downE
        var box = document.querySelector('#box')
        box.addEventListener('mousedown', mouse_down)
        function mouse_down(e) {
            downE = e || window.event
            document.addEventListener('mousemove', mouse_move)
            document.addEventListener('mouseup', mouse_up)
        }

        function mouse_move(e) {
            var moveE = e || window.event
            var l = moveE.pageX - downE.offsetX
            var t = moveE.pageY - downE.offsetY
            if (l <= 0) {
                l = 0
            }
            if (l > document.documentElement.clientWidth - box.clientWidth) {
                l = document.documentElement.offsetWidth - box.clientWidth
            }
            box.style.left = l + 'px'
            if (t <= 0) {
                t = 0
            }
            if (t > document.documentElement.clientHeight - box.offsetHeight) {
                t = document.documentElement.clientHeight - box.offsetHeight
            }
            box.style.top = t + 'px'
        }

        function mouse_up () {
            document.removeEventListener('mousemove', mouse_move)
            document.removeEventListener('mouseup', mouse_up)
        }
    </script>
</body>

</html>